package com.heima.schedule.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author shiminghui
 * @date 2024/12/1 10:28
 * @description: TODO
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task
     * @return
     */
    @Override
    public Long addTask(Task task) {

        // 添加任务到数据库
        boolean successDb = addTaskToDb(task);
        if (!successDb) {
            log.error("添加任务到数据库失败");
            return null;
        }

        // 添加任务到redis
        boolean successCache = addTaskToCache(task);
        if (!successCache) {
            log.error("添加任务到redis失败");
        }

        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId) {

        // 删除数据库任务,并更新任务日志为已取消
        Task task = updateTaskOnDb(taskId, ScheduleConstants.CANCELLED);
        if (task == null) {
            log.error("删除数据库任务失败");
            return false;
        }
        // 删除redis任务
        boolean successCache = deleteTaskOnCache(task);
        if (!successCache) {
            log.error("删除redis任务失败");
            return false;
        }

        return true;
    }

    /**
     * 根据类型和优先级获取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task getTask(int type, int priority) {
        // 获取任务的key
        String key = type + "_" + priority;
        String topicKey = ScheduleConstants.TOPIC + key;

        // 查询redis
        try {
            String taskId = cacheService.lRightPop(topicKey);
            if (taskId != null) {
                // 查询数据库
                Taskinfo taskinfo = taskinfoMapper.selectById(taskId);
                if (taskinfo == null) {
                    log.info("数据库中不存在该任务,该任务可能已被删除");
                    return null;
                }

                // 消费任务

                // 更新任务状态
                Task task = updateTaskOnDb(taskinfo.getTaskId(), ScheduleConstants.EXECUTED);
                return task;
            }
        } catch (Exception e) {
            log.error("从redis获取任务失败", e);
        }

        return null;
    }

    /**
     * 定时刷新任务
     */
    @Override
    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void refresh() {
        // 分布式同步问题解决(使用的redis的sexnx)
        String value = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30); // 30秒
        if (value == null) {
            log.info("获取锁失败");
            return;
        }

        // 从redis的zset表中获取需要执行的任务
        Set<String> keys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        for (String key : keys) {
            // 根据key获取任务类型和优先级
            String typeAndPriority = key.split(ScheduleConstants.FUTURE)[1];
            // 拼接任务key
            String topicKey = ScheduleConstants.TOPIC + typeAndPriority;

            // 从zset表查询数据
            Set<String> taskIds = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());
            // 将这些数据添加到redis的list中
            if (taskIds != null && !taskIds.isEmpty()) {
                cacheService.refreshWithPipeline(key, topicKey, taskIds);
                log.info("刷新任务到redis成功,源任务的key为{},目的任务的key为{}", key, topicKey);
            }
        }
    }

    /**
     * 定时任务(将数据库中的任务信息同步到redis)
     */
    @Override
    @PostConstruct  // 项目启动时执行一次
    @Scheduled(cron = "0 0/5 * * * ? ") // 每5分钟执行一次
    public void syncSchedule() {
        // 清空redis缓存
        clearCache();

        // 查询数据库的任务信息
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        Date presetTime = calendar.getTime();

        List<Taskinfo> taskList = taskinfoMapper.selectList(Wrappers.lambdaQuery(Taskinfo.class).le(Taskinfo::getExecuteTime, presetTime));
        if (taskList == null || taskList.isEmpty()) {
            return;
        }

        // 将任务添加到redis
        for (Taskinfo taskinfo : taskList) {
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo, task);
            boolean b = addTaskToCache(task);
            if (!b) {
                log.error("任务{}同步到redis失败", taskinfo.getTaskId());
            }
        }

    }

    /**
     * 清空redis缓存
     */
    void clearCache() {
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
        log.info("redis 清理task缓存成功");
    }

    /**
     * 删除redis任务
     *
     * @param task
     * @return
     */
    private boolean deleteTaskOnCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        try {
            if (task.getExecuteTime() <= System.currentTimeMillis()) {
                cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, task.getTaskId().toString());
            } else if (task.getExecuteTime() <= LocalDateTime.now().plusMinutes(5).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()) {
                cacheService.zRemove(ScheduleConstants.FUTURE + key, task.getTaskId().toString());
            }
            return true;
        } catch (Exception e) {
            log.error("从redis删除任务{}失败", task.getTaskId(), e);
            return false;
        }
    }

    /**
     * 删除数据库任务,并更新任务日志为已取消
     *
     * @return
     */
    private Task updateTaskOnDb(Long taskId, Integer taskStatus) {
        //查询任务
        Taskinfo taskinfo = taskinfoMapper.selectById(taskId);
        if (taskinfo == null) {
            log.error("任务不存在");
            return null;
        }
        //删除任务
        int delete = taskinfoMapper.deleteById(taskId);
        if (delete <= 0) {
            log.error("删除任务失败");
            return null;
        }
        //更新任务日志
        int update = taskinfoLogsMapper.update(null, Wrappers.lambdaUpdate(TaskinfoLogs.class)
                .eq(TaskinfoLogs::getTaskId, taskId)
                .set(TaskinfoLogs::getStatus, taskStatus));
        if (update <= 0) {
            log.error("更新任务日志失败");
            return null;
        }
        Task task = new Task();
        BeanUtils.copyProperties(taskinfo, task);
        task.setExecuteTime(taskinfo.getExecuteTime().getTime());
        return task;
    }

    /**
     * 添加任务到redis
     *
     * @param task
     * @return
     */
    private boolean addTaskToCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        // 执行时间小于等于当前时间
        try {
            if (task.getExecuteTime() <= System.currentTimeMillis()) { //立即执行
                cacheService.lLeftPush(ScheduleConstants.TOPIC + key, task.getTaskId().toString());
            } else if (task.getExecuteTime() <= LocalDateTime.now().plusMinutes(5).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()) { //预设时间执行
                cacheService.zAdd(ScheduleConstants.FUTURE + key, task.getTaskId().toString(), task.getExecuteTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 添加任务到数据库
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        try {
            // 添加任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));

            int insert = taskinfoMapper.insert(taskinfo);
            if (insert <= 0) {
                return false;
            }

            task.setTaskId(taskinfo.getTaskId());

            //添加任务日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            int insert1 = taskinfoLogsMapper.insert(taskinfoLogs);
            if (insert1 <= 0) {
                return false;
            }

            return true;
        } catch (BeansException e) {
            e.printStackTrace();
            return false;
        }
    }
}
